import { NextRequest, NextResponse } from 'next/server';
import { mockTickets, generateMockTicket } from '@/mock/tickets';
import { Ticket, CreateTicketRequest, TicketFilters, PaginatedResponse, ApiResponse } from '@/types/ticket';

// 模拟数据存储
let tickets: Ticket[] = [...mockTickets];

// GET /api/tickets - 获取工单列表
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    
    // 解析查询参数
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = parseInt(searchParams.get('pageSize') || '10');
    const status = searchParams.get('status')?.split(',');
    const priority = searchParams.get('priority')?.split(',');
    const category = searchParams.get('category')?.split(',');
    const assignee = searchParams.get('assignee')?.split(',');
    const search = searchParams.get('search');

    // 过滤工单
    let filteredTickets = tickets;

    if (status?.length) {
      filteredTickets = filteredTickets.filter(ticket => status.includes(ticket.status));
    }

    if (priority?.length) {
      filteredTickets = filteredTickets.filter(ticket => priority.includes(ticket.priority));
    }

    if (category?.length) {
      filteredTickets = filteredTickets.filter(ticket => category.includes(ticket.category));
    }

    if (assignee?.length) {
      filteredTickets = filteredTickets.filter(ticket => 
        ticket.assignee && assignee.includes(ticket.assignee)
      );
    }

    if (search) {
      const searchLower = search.toLowerCase();
      filteredTickets = filteredTickets.filter(ticket =>
        ticket.title.toLowerCase().includes(searchLower) ||
        ticket.description.toLowerCase().includes(searchLower) ||
        ticket.tags?.some(tag => tag.toLowerCase().includes(searchLower))
      );
    }

    // 排序（按创建时间倒序）
    filteredTickets.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());

    // 分页
    const total = filteredTickets.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedTickets = filteredTickets.slice(startIndex, endIndex);

    const response: ApiResponse<PaginatedResponse<Ticket>> = {
      success: true,
      data: {
        data: paginatedTickets,
        total,
        page,
        pageSize,
      },
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取工单列表失败:', error);
    return NextResponse.json(
      { success: false, message: '获取工单列表失败' },
      { status: 500 }
    );
  }
}

// POST /api/tickets - 创建新工单
export async function POST(request: NextRequest) {
  try {
    const body: CreateTicketRequest = await request.json();

    // 验证必填字段
    if (!body.title || !body.description) {
      return NextResponse.json(
        { success: false, message: '标题和描述为必填字段' },
        { status: 400 }
      );
    }

    // 创建新工单
    const newTicket = generateMockTicket({
      title: body.title,
      description: body.description,
      priority: body.priority,
      category: body.category,
      assignee: body.assignee,
      dueDate: body.dueDate,
      tags: body.tags,
      reporter: '当前用户', // 实际项目中从认证信息获取
    });

    // 添加到数据存储
    tickets.unshift(newTicket);

    const response: ApiResponse<Ticket> = {
      success: true,
      data: newTicket,
      message: '工单创建成功',
    };

    return NextResponse.json(response, { status: 201 });
  } catch (error) {
    console.error('创建工单失败:', error);
    return NextResponse.json(
      { success: false, message: '创建工单失败' },
      { status: 500 }
    );
  }
} 